﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml.Linq;
using System.Text.RegularExpressions;

namespace vkontakte_client
{
    /// <summary>
    /// Класс для работы с XML.
    /// </summary>
    class XML
    {
        /// <summary>
        /// Функция, преобразующая XML документ в коллекцию ключей и значений.
        /// </summary>
        /// <param name="s">XML документ</param>
        /// <returns>dictionary string - string</returns>
        public static Dictionary<string, string> Parse(string s)
        {
            XDocument doc = XDocument.Parse(s);
            Dictionary<string, string> dataDictionary = new Dictionary<string, string>();
            foreach (XElement element in doc.Descendants().Where(p => p.HasElements == false))
            {
                int keyInt = 0;
                string keyName = element.Name.LocalName;

                while (dataDictionary.ContainsKey(keyName))
                    keyName = element.Name.LocalName + "_" + keyInt++;

                dataDictionary.Add(keyName, element.Value);
            }
            return dataDictionary;
        }
        public static System.Collections.ArrayList Field_Parse(string s, string tag_name)
        {
            System.Collections.ArrayList dataList = new System.Collections.ArrayList();
            string Search_pattern = "<" + tag_name + ">+[0-9]+</" + tag_name + ">+";
            Regex Search_regex = new Regex(Search_pattern);
            System.Text.RegularExpressions.MatchCollection Matches = Search_regex.Matches(s);
            foreach (System.Text.RegularExpressions.Match Match in Matches)
            {
                string Match_string = ((s.Substring(Match.Index, Match.Length)).Replace("</" + tag_name + ">", "")).Replace("<" + tag_name + ">", "");
                dataList.Add(Match_string);               
            }
            return dataList;
        }
    }
}
